import json
import math

def wgs84_to_gcj02(lng, lat):
    """
    WGS84坐标系转GCJ02坐标系(火星坐标系)
    :param lng: WGS84经度
    :param lat: WGS84纬度
    :return: GCJ02经纬度
    """
    a = 6378245.0  # 长半轴
    ee = 0.00669342162296594323  # 扁率
    
    # 判断是否在国内
    if (lng < 72.004 or lng > 137.8347) or (lat < 0.8293 or lat > 55.8271):
        return lng, lat
    
    # 转换算法
    dlat = transform_lat(lng - 105.0, lat - 35.0)
    dlng = transform_lng(lng - 105.0, lat - 35.0)
    
    radlat = lat / 180.0 * math.pi
    magic = math.sin(radlat)
    magic = 1 - ee * magic * magic
    sqrtmagic = math.sqrt(magic)
    
    dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * math.pi)
    dlng = (dlng * 180.0) / (a / sqrtmagic * math.cos(radlat) * math.pi)
    
    mglat = lat + dlat
    mglng = lng + dlng
    
    return mglng, mglat

def transform_lat(x, y):
    ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * math.sqrt(abs(x))
    ret += (20.0 * math.sin(6.0 * x * math.pi) + 20.0 * math.sin(2.0 * x * math.pi)) * 2.0 / 3.0
    ret += (20.0 * math.sin(y * math.pi) + 40.0 * math.sin(y / 3.0 * math.pi)) * 2.0 / 3.0
    ret += (160.0 * math.sin(y / 12.0 * math.pi) + 320 * math.sin(y * math.pi / 30.0)) * 2.0 / 3.0
    return ret

def transform_lng(x, y):
    ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * math.sqrt(abs(x))
    ret += (20.0 * math.sin(6.0 * x * math.pi) + 20.0 * math.sin(2.0 * x * math.pi)) * 2.0 / 3.0
    ret += (20.0 * math.sin(x * math.pi) + 40.0 * math.sin(x / 3.0 * math.pi)) * 2.0 / 3.0
    ret += (150.0 * math.sin(x / 12.0 * math.pi) + 300.0 * math.sin(x / 30.0 * math.pi)) * 2.0 / 3.0
    return ret

def convert_geojson(input_file, output_file):
    """
    转换GeoJSON文件中的坐标
    :param input_file: 输入文件路径
    :param output_file: 输出文件路径
    """
    with open(input_file, 'r', encoding='utf-8') as f:
        data = json.load(f)
    
    # 遍历所有features
    for feature in data['features']:
        geometry = feature['geometry']
        if geometry['type'] == 'MultiPolygon':
            # 转换每个多边形中的坐标
            for polygon in geometry['coordinates']:
                for ring in polygon:
                    for i in range(len(ring)):
                        lng, lat = ring[i]
                        ring[i] = wgs84_to_gcj02(lng, lat)
    
    # 保存转换后的文件
    with open(output_file, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

if __name__ == '__main__':
    input_path = r"c:\Users\11987\Downloads\晋江市.json"
    output_path = r"c:\Users\11987\Downloads\晋江市_gcj02.json"
    convert_geojson(input_path, output_path)
    print(f"转换完成，结果已保存到: {output_path}")